/**
 * 酷盘控制类的单例
 * @author William
 * 2012-5-10
 */
package com.ytu.clouddisk.kanbox;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.LevelListDrawable;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.ytu.clouddisk.face.BrowserActivity;
import com.ytu.clouddisk.face.CloudDiskLoginActivity;
import com.ytu.clouddisk.face.LVAdapter;
import com.ytu.clouddisk.face.ListViewItemData;
import com.ytu.clouddisk.face.R;
import com.ytu.clouddisk.face.Varibles;
import com.ytu.clouddisk.kanbox.api.Kanbox;
import com.ytu.clouddisk.kanbox.api.KanboxException;
import com.ytu.clouddisk.kanbox.api.RequestListener;
import com.ytu.clouddisk.kanbox.api.Token;

public class KanBoxControl implements View.OnClickListener, RequestListener {

	private static KanBoxControl instance;
	private Context mContext;

	public static KanBoxControl getInstance(Context m) {
		instance = new KanBoxControl(m);
		return instance;
	}

	/**
	 * 构造函数
	 * 
	 * @param c
	 */
	private KanBoxControl(Context c) {
		mContext = c;
	}

	/**
	 * 请求用户授权
	 */
	public void getOauth() {
		Intent sIntent = new Intent(mContext, KanBoxWebLogin.class);
		String kanBoxUrl = "https://auth.kanbox.com/0/auth?response_type=code&client_id="
				+ Varibles.KANBOX_CLIENT_ID
				+ "&platform=android"
				+ "&redirect_uri="
				+ Varibles.KANBOX_REDIRECT_URI
				+ "&user_language=ZH";
		sIntent.putExtra("url", kanBoxUrl);
		mContext.startActivity(sIntent);
	}

	/**
	 * 刷新access_token
	 */
	private void refreshAccessToken() {
		try {
			Token.getInstance(mContext).refreshToken(Varibles.KANBOX_CLIENT_ID,
					Varibles.KANBOX_CLIENT_KEY, KanBoxControl.this);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			Toast.makeText(mContext, "操作失败\n\n" + e.toString(),
					Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * 获取帐号信息
	 */
	private void getAccountInfo() {
		Kanbox.getInstance().getAccountInfo(Token.getInstance(mContext),
				KanBoxControl.this);
	}

	/**
	 * 获取文件列表 假设路径为“/照片”
	 */
	public void getFileList() {
		// Token token = Token.getInstance(mContext);
		Kanbox.getInstance().getFileList(Token.getInstance(mContext), "/",
				KanBoxControl.this);
		Toast.makeText(mContext,"DDDDDDD",Toast.LENGTH_SHORT).show();
	}

	/**
	 * 移动文件
	 */
	private void moveFile() {
		Kanbox.getInstance().moveFile(Token.getInstance(mContext),
				"/kanbox.png", "/kanbox/kanbox.png", KanBoxControl.this);
	}

	/**
	 * 复制文件
	 */
	private void copyFile() {
		Kanbox.getInstance().copyFile(Token.getInstance(mContext),
				"/kanbox/kanbox.png", "/kanbox.png", KanBoxControl.this);
	}

	/**
	 * 删除文件
	 */
	private void deleteFile() {
		Kanbox.getInstance().deleteFile(Token.getInstance(mContext),
				"/kanbox.png", KanBoxControl.this);
	}

	/**
	 * 创建文件夹
	 */
	private void makeDir() {
		Kanbox.getInstance().makeDir(Token.getInstance(mContext), "/kanbox",
				KanBoxControl.this);
	}

	/**
	 * 创建共享文件夹
	 */
	private void makeShareDir() {
		ArrayList<String> mails = new ArrayList<String>();
		mails.add("test@test.com");
		try {
			Kanbox.getInstance().makeShareDir(mails,
					Token.getInstance(mContext), "/kanbox", KanBoxControl.this);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			Toast.makeText(mContext, "操作失败\n\n" + e.toString(),
					Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * 获取共享邀请列表
	 */
	private void getShareInviteList() {
		Kanbox.getInstance().getShareInviteList(Token.getInstance(mContext),
				KanBoxControl.this);
	}

	/**
	 * 处理共享请求
	 */
	private void handleShareInvite() {
		try {
			String shareDir = "/sssss";
			String invite = "test@test.com";
			boolean accept = true; // true:接受，false：拒绝
			Kanbox.getInstance().handleShareInvite(shareDir, invite, accept,
					Token.getInstance(mContext), KanBoxControl.this);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			Toast.makeText(mContext, "操作失败\n\n" + e.toString(),
					Toast.LENGTH_LONG).show();
		} catch (JSONException e) {
			e.printStackTrace();
			Toast.makeText(mContext, "操作失败\n\n" + e.toString(),
					Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * 是否是自己创建的共享文件夹
	 */
	private void checkSharedOwner() {
		Kanbox.getInstance().checkSharedOwner(Token.getInstance(mContext),
				"/kanbox", KanBoxControl.this);
	}

	/**
	 * 下载文件
	 */
	private void downloadFile() {
		Kanbox.getInstance().download("/kanbox.png", "/sdcard/download.png",
				Token.getInstance(mContext), KanBoxControl.this);
	}

	/**
	 * 上传文件
	 */
	private void uploadFile() {
		try {
			Kanbox.getInstance().upload("/sdcard/kanbox.png", "/upload.png",
					Token.getInstance(mContext), KanBoxControl.this);
		} catch (IOException e) {
			e.printStackTrace();
			Toast.makeText(mContext, "操作失败\n\n" + e.toString(),
					Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void downloadProgress(long currSize) {
		Toast.makeText(mContext, "已传输：" + currSize, Toast.LENGTH_SHORT).show();
	}

	private void handleResponse(String response) {
		try {
			JSONObject sData = new JSONObject(response);
			String status = sData.getString("status");
			if (status.equals("ok")) {
				Toast.makeText(mContext, "操作成功\n\n" + response,
						Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(mContext, "操作失败\n\n" + response,
						Toast.LENGTH_LONG).show();
			}
		} catch (JSONException e) {
			Toast.makeText(mContext, "操作失败\n\n" + e.toString(),
					Toast.LENGTH_LONG).show();
		}
	}

	public void saveToken(Token token) {
		PushSharePreference sPreference = new PushSharePreference(mContext,
				Varibles.CONFIG_FILE);
		sPreference.saveStringValueToSharePreferences(
				Varibles.KANBOX_ACCESS_TOKEN, token.getAcceccToken());
		sPreference.saveStringValueToSharePreferences(
				Varibles.KANBOX_REFRESH_TOKEN, token.getRefreshToken());
		sPreference.saveLongValueToSharePreferences("expries",
				token.getExpires());
	}

	public void loadToken() {
		PushSharePreference sPreference = new PushSharePreference(mContext,
				Varibles.CONFIG_FILE);
		Token sToken = Token.getInstance(mContext);
		sToken.setAcceccToken(sPreference
				.getStringValueByKey(Varibles.KANBOX_ACCESS_TOKEN));
		sToken.setRefreshToken(sPreference
				.getStringValueByKey(Varibles.KANBOX_REFRESH_TOKEN));
		sToken.setExpires(sPreference.getLongValueByKey("expries"));
	}

	@Override
	public void onComplete(String response, int operationType) {
		switch (operationType) {
		case OP_REFRESH_TOKEN:
			try {
				Token.getInstance(mContext).parseToken(response);
				Toast.makeText(mContext, "刷新token成功\n\n" + response,
						Toast.LENGTH_LONG).show();
				saveToken(Token.getInstance(mContext));
			} catch (JSONException e) {
				e.printStackTrace();
				Toast.makeText(mContext, "刷新token失败\n\n" + response,
						Toast.LENGTH_LONG).show();
			}
			return;
		case OP_UPLOAD:
			Toast.makeText(mContext, "上传成功\n\n" + response, Toast.LENGTH_LONG)
					.show();
			return;
		case OP_DOWNLOAD:
			Toast.makeText(mContext, "下载成功\n\n" + response, Toast.LENGTH_LONG)
					.show();
			return;
		case OP_GET_FILELIST:
			try {
				JSONObject sData = new JSONObject(response);
				String status = sData.getString("status");
				if (status.equals("ok")) {
					String contents = sData.getString("contents");
					JSONArray list = new JSONArray(contents);
					List<String> DocsNames = new ArrayList<String>();

					for (int i = 1; i < list.length(); i++) {
						JSONObject jsonObj = new JSONObject();
						jsonObj = list.getJSONObject(i);
						DocsNames.add(jsonObj.getString("fullPath"));
					}
					LevelListDrawable levelListDrawable = (LevelListDrawable) mContext
							.getResources().getDrawable(
									R.drawable.listview_image_file); // 获取图片列表
					ListViewItemData mListViewItemData = new ListViewItemData(
							levelListDrawable, DocsNames, DocsNames.size());

					ListView mListView = BrowserActivity.getListView();
					LVAdapter mListViewAdapter = new LVAdapter(mContext,
							mListViewItemData);
					mListView.setAdapter(mListViewAdapter);
				} else {
					Toast.makeText(mContext, "操作失败\n\n" + response,
							Toast.LENGTH_LONG).show();
				}
			} catch (JSONException e) {
				Toast.makeText(mContext, "操作失败\n\n" + e.toString(),
						Toast.LENGTH_LONG).show();
			}
         break;
		default:
			handleResponse(response);
			return;
		}
	}

	@Override
	public void onError(KanboxException error, int operationType) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub

	}

}
